#include "nlohmann/json.hpp"
#include "Encode.hpp"

#include <fstream>
#include <windows.h>
#include <string>
#include <map>
#include <iostream>
#include <filesystem>

using namespace std;
using namespace std::filesystem;
using json = nlohmann::json;

// #define DEBUG
#ifdef DEBUG
#define dout cout
#else
#define dout 0 && cout
#endif

int wirteREG(string pathvalue)
{
    HKEY hKey = NULL;
    LPTSTR lpValue = NULL;
    DWORD dwType = 0;
    DWORD dwValueSize = 0;

    // 打开键值

    if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SYSTEM\\ControlSet001\\Control\\Session Manager\\Environment", 0, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
    {
        cout <<"RegOpenKeyExA is Not Open!"<<endl;
        cout <<UTF8_GBK("请将该程序设为管理员权限!")<<endl;
        return 1;
    }

    if (RegSetValueExA(hKey, "Path", 0, REG_EXPAND_SZ, (LPBYTE)pathvalue.c_str(), pathvalue.size()) != ERROR_SUCCESS)
    {
        cout << "RegSetValueEx ERROR\n" << endl;
        free(lpValue);
        RegCloseKey(hKey);
        return 1;
    }
    RegCloseKey(hKey);
    return 0;
}

int main()
{
    string strInput;
    int intInput;
    map<int, string> mapEnvs;

    // 读配置文件
    ifstream f=NULL;
    f.open("config.json");
    if(!f){
        cout <<UTF8_GBK("打开配置文件错误!")<<endl;
        system("pause");
        return 2;
    }
    json jsConfig = json::parse(f);
    dout << jsConfig << endl;

    // 储存配置数据
    json::iterator c = jsConfig.begin();
    for (std::size_t i = 1; i <= jsConfig.size(); ++i)
    {
        mapEnvs[i] = c.key();
        c++;
    }

    dout << mapEnvs[1] << endl;

    // 请用户选择
    while (1)
    {
        for (int i = 1; i <= mapEnvs.size(); i++)
        {
            cout << to_string(i) + ". " << mapEnvs[i] << endl;
        }
        cout << UTF8_GBK("请输入以上环境的序号: ");
        cin >> strInput;
        intInput = atoi(strInput.c_str()); // 字母转为0
        if (0 == intInput)
        {
            cout << UTF8_GBK("请输入数字.") << endl;
            system("pause");
            continue;
        }
        if (intInput > mapEnvs.size())
        {
            cout << UTF8_GBK("没有这个序号.") << endl;
            system("pause");
            continue;
        }
        break;
    }

    string strNewPath;

    if ("default" == mapEnvs[intInput])
    {
        strNewPath = jsConfig["default"];
    }
    else
    {
        strNewPath = jsConfig["default"];
        strNewPath.append(";");
        strNewPath.append(string(jsConfig[mapEnvs[intInput]]));
    }    
    dout << strNewPath << endl;
    if(1 == wirteREG(strNewPath)){
        cout <<UTF8_GBK("写入注册表错误!")<<endl;
        system("pause");
        return 3;
    }
    cout <<UTF8_GBK("已将系统变量Path设置为: ")<< strNewPath <<endl;
    system("pause");
    return 0;
}